import { forwardRef, useEffect, useState, useImperativeHandle, useMemo } from 'react';
import {commonLang} from '@inbiz/utils'
import { connect, useField, mapProps } from '@formily/react';
import { Field } from '@formily/core';
import moment, { Moment } from 'moment';
import { ConfigProvider, DatePicker } from 'antd';
import { getMessage, TextWidget } from '@inbiz/react';
import { useEvents } from '@inbiz/utils';
import { defaultProps } from '../../designer/schema';
import api from './api';
import './style.less';
import { GlobalRegistry } from '@inbiz/core';

type IProps = {
  callBackEvents?: {
    onBeforeChange?: (v: string) => boolean;
  };
  value?: any;
  onChange?: any;
  readOnly?: boolean;
  disabled?: boolean;
  viewMode?:string;
  emit?: {
    /* 点击确定按钮时触发 */
    (type: 'onOk', value?: Moment): void;
    /* 弹出日历和关闭日历 */
    (type: 'onOpenChange', value?: Moment): void;
  };
} & typeof defaultProps;


const EformDatePickerContent = forwardRef((props: IProps, ref) => {
  const { callBackEvents, emit, value, placeholder,viewMode, ...other } = props;
  const [configEvents] = useEvents(props.callBackEvents, props.emit);
  const field = useField<Field>();
  const [locale, $locale] = useState(commonLang[GlobalRegistry.getDesignerLanguage()?.toLocaleLowerCase() as keyof typeof commonLang])
  useImperativeHandle(
    ref,
    () => ({
      ...api(configEvents, props),
    }),
    [props.value],
  );
  useEffect(() => {
    // 验证是否满足 允许小于当前时间，最小值，最大值
    field.setValidatorRule('validator', (value: Date, rule: any, ctx: any) => {
      const format = ctx.field.componentProps.format;
      const validValue = [
        {
          indexV: 's',
          accurate: 'second',
          format: 'YYYY-MM-DD HH:mm:ss',
        },
        {
          indexV: 'm',
          accurate: 'minute',
          format: 'YYYY-MM-DD HH:mm',
        },
        {
          indexV: 'H',
          accurate: 'hour',
          format: 'YYYY-MM-DD HH',
        },
        {
          indexV: 'D',
          accurate: 'day',
          format: 'YYYY-MM-DD',
        },
        {
          indexV: 'M',
          accurate: 'month',
          format: 'YYYY-MM',
        },
        {
          indexV: 'Y',
          accurate: 'year',
          format: 'YYYY',
        },
      ];
      const arr = ['s', 'm', 'H', 'D', 'M', 'Y'];
      let nowIndex = 's';
      for (let index = 0; index < arr.length; index++) {
        if (format.indexOf(arr[index]) !== -1) {
          nowIndex = arr[index];
          break;
        }
      }
      let accurate = validValue.filter((item) => {
        return item.indexV === nowIndex;
      })[0].accurate;
      // 是否允许小于当前时间
      if (!ctx.field.componentProps.allowBeforeNow) {
        if (value && moment(value) < moment().startOf(accurate as any)) {
          // return (getMessage('EformDatePicker.validate.DateNotAllowSmallThanNow'));
          return <TextWidget>EformDatePicker.validate.DateNotAllowSmallThanNow</TextWidget>;
        }
      }

      // 最小值
      if (value && ctx.field.componentProps.min) {
        for (let i = 0; i < validValue.length; i++) {
          if (format?.indexOf(validValue[i].indexV) != -1) {
            if (
              moment(value) <
              moment(ctx.field.componentProps.min).startOf(validValue[i].accurate as any)
            ) {
              // return (
              //   getMessage('EformDatePicker.validate.dateCannotLessThan') +
              //   moment(ctx.field.componentProps.min).format(props.format)
              // );
              return (
                <>
                  <TextWidget>EformDatePicker.validate.dateCannotLessThan</TextWidget>
                  {moment(ctx.field.componentProps.min).format(props.format)}
                </>
              );
            }
          }
        }
      }
      // 最大值
      if (value && ctx.field.componentProps.max) {
        for (let i = 0; i < validValue.length; i++) {
          if (format?.indexOf(validValue[i].indexV) != -1) {
            if (
              moment(value) >
              moment(ctx.field.componentProps.max).endOf(validValue[i].accurate as any)
            ) {
              // return (
              //   getMessage('EformDatePicker.validate.dateCannotMoreThan') +
              //   moment(ctx.field.componentProps.max).format(props.format)
              // );
              return (
                <>
                  <TextWidget>EformDatePicker.validate.dateCannotMoreThan</TextWidget>
                  {moment(ctx.field.componentProps.max).format(props.format)}
                </>
              );
            }
          }
        }
      }
      return true;
    });
  }, []);

  useEffect(() => {
    $locale(commonLang[GlobalRegistry.getDesignerLanguage()?.toLocaleLowerCase() as keyof typeof commonLang])
  }, [GlobalRegistry.getDesignerLanguage()])

  // 所有的方法。
  const onOk = () => {
    props.emit?.('onOk');
  };
  const onChange = (value: any) => {
    props.onChange(value ? new Date(value) : null);
  };

  //弹出日历和关闭日历
  const onOpenChange = () => {
    props.emit?.('onOpenChange', props.value);
  };
  const picker = useMemo(() => {
    if (props.format.includes('D')) {
      return 'date';
    }
    if (props.format.includes('M')) {
      return 'month';
    }
    return 'year';
  }, [props.format]);

  return (
    <ConfigProvider locale={locale}>
      {viewMode=='look'?value?moment(props.value).format(props.format):'':
            <DatePicker
            {...other}
            className={'eformDatePicker'}
            // getPopupContainer={(triggerNode) => document.querySelector('.dn-preview-panel') || document.body}
            dropdownClassName="clearSpaceOccupation"
            inputReadOnly={true}
            disabled={props.readOnly || props.disabled}
            value={value ? moment(value) : undefined}
            placeholder={placeholder}
            showTime={
              props.format?.indexOf('s') != -1 ||
                props.format?.indexOf('m') != -1 ||
                props.format?.indexOf('H') != -1
                ? { format: props.format?.split(' ')[1] }
                : false
            }
            picker={picker}
            // disabledDate={(current) => {
            //   //设置最大最小可选日期
            //   if (props) {
            //     const min = current < moment(props.min).endOf('day') //最小值
            //     const max = current > moment(props.max).endOf('day') //最大值
            //     const allowBeforeNow = props.allowBeforeNow ? false : current < moment().endOf('day') //是否允许小于当前时间
            //     return current && min || max || allowBeforeNow
            //   } else {
            //     return false
            //   }
            // }}
            onChange={onChange}
            onOk={onOk}
            onOpenChange={onOpenChange}
          />}

    </ConfigProvider>
  );
});
EformDatePickerContent.displayName = 'EformDatePickerContent';

(
  EformDatePickerContent as typeof EformDatePickerContent & IDefaultValueFormat<typeof defaultProps>
).originValueFormat = (value: any, props: object) => {
  return value && new Date(value);
};
(
  EformDatePickerContent as typeof EformDatePickerContent & IDefaultValueFormat<typeof defaultProps>
).defaultValueFormat = (props: any): null | Date | void => {
  if (props.defaultValueType == 'customDefaultValue') {
    if (props.customDefaultValue) {
      return new Date(props.customDefaultValue);
    } else {
      return null;
    }
  } else {
    if (props.variableDefaultValue == 'nowTime') {
      return new Date();
    }
  }
};
export default connect(
  EformDatePickerContent,
  mapProps((props: IProps) => {
    const others = props;
    others.placeholder = getMessage(props.placeholder);
    return { ...others };
  }),
);

export type { IProps };
